package com.ecube.maintenance.biz.commons;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.LruCache;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.ecube.maintenance.utils.BaseParameters;
import com.ecube.maintenance.utils.VolleyUtils;

import java.lang.reflect.Type;

/**
 * Created by Trible Chen on 2014/9/5.
 */
public class VolleySingleton {

    private RequestQueue mRequestQueue,mImageRequestQueue;
    private ImageLoader mImageLoader;
    static Context mContext;
    static VolleySingleton mInstance;
    static Object mLock = new Object();

    public static void init(Context context){
        mContext = context;
    }
    public static VolleySingleton getInstance(){
        if(mInstance == null){
            synchronized(mLock){
                if(mInstance == null){
                    mInstance = new VolleySingleton();
                }
            }
        }
        return mInstance;
    }
    private VolleySingleton() {
        mRequestQueue = getRequestQueue();
        mImageRequestQueue = getRequestQueue();
        mImageLoader = new ImageLoader(mImageRequestQueue,
        new ImageLoader.ImageCache(){
            private final LruCache<String,Bitmap> cache
                    = new LruCache<String,Bitmap>(1*1024*1024);
            @Override
            public Bitmap getBitmap(String url){
                return cache.get(url);
            }
            @Override
            public void putBitmap(String url,Bitmap bitmap){
                cache.put(url,bitmap);
            }
        });
    }

    public RequestQueue getRequestQueue(){
        if(mRequestQueue == null){
            //getApplication()方法返回一个当前进程的全局应用上下文，这就意味着
            //它的使用情景为：你需要一个生命周期独立于当前上下文的全局上下文，
            //即就是它的存活时间绑定在进程中而不是当前某个组建。
            //mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
        }
        return Volley.newRequestQueue(mContext.getApplicationContext());
    }

    private <T> void addToRequestQueue(Request<T>req){
        mRequestQueue.add(req);
    }
    public <T> void addToRequestQueue(BaseParameters p,ICCallBack<T> callBack,
                                      Type callbackType,ITestDataProvider... provider){

        VolleyCallbackAdapter<T> adapter = new VolleyCallbackAdapter<T>(callBack,callbackType,provider);
        StringRequest req = VolleyUtils.getPostRequest(
                Constants.getURL(), p, adapter, adapter);
        VolleySingleton.getInstance().addToRequestQueue(req);
    }
    public ImageLoader getImageLoader(){
        return mImageLoader;
    }
    public static void loadImage(String url,ImageLoader.ImageListener listener){
        getInstance().getImageLoader().get(url,listener);
    }
}
